package com.yourname.myapplication.presentation.screen.quiz
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import com.yourname.myapplication.data.repository.QuestionRepository
import com.yourname.myapplication.domain.extensions.toDomainModel
import com.yourname.myapplication.domain.model.Question
import kotlinx.coroutines.flow.map

class QuizViewModel(
    internal val repository: QuestionRepository
) : ViewModel() {
    // 题目列表（自动更新）
    val questions: LiveData<List<Question>> = repository.getAllQuestions()
        .map { list -> list.map { it.toDomainModel() } }
        .asLiveData()

    // 当前题目索引
    val _currentIndex = MutableLiveData(0)
    val currentIndex: LiveData<Int> = _currentIndex

    // 分数
    val _score = MutableLiveData(0)
    val score: LiveData<Int> = _score

    // 检查答案
    fun checkAnswer(selectedIndex: Int) {
        val currentQuestion = questions.value?.getOrNull(currentIndex.value ?: 0) ?: return
        if (selectedIndex == currentQuestion.answer) {
            _score.value = (_score.value ?: 0) + 10
        }
        nextQuestion()
    }

    // 下一题
    private fun nextQuestion() {
        val nextIndex = (_currentIndex.value ?: 0) + 1
        if (nextIndex < (questions.value?.size ?: 0)) {
            _currentIndex.value = nextIndex
        }
    }
}